import React, {useState, useEffect} from "react";


function FunctionState() {

    const initialTimer = 2;


    const [timer, setTimer] = useState(initialTimer);
    const [hello, setHello] = useState('hi');

    // useEffect(() => {
    //     // console.log('useEffect 被执行')
    //    const interval = setInterval(() => {
    //         // console.log('Timer + 1')
    //         setTimer(oldTimer => oldTimer + 1);
    //     }, 1000);

    //     return() => {
    //         clearInterval(interval);
    //     }
        
    // }, []);

    useEffect(() => {

        const timeOut = setTimeout(() => {
            setTimer(timer + 1);
            setHello(hello + 'i');
        }, 1000);

        return () => clearTimeout(timeOut);

    }, [timer, hello]);

    const onX2 = () => {
        setTimer(timer * 2)
    }

    const onMinus1 = () => {
        setTimer(timer - 1)
    }

    const onReset = () => {
        setTimer(initialTimer)
    }

    return (
        <>
            <button onClick={onX2}>x2</button>
            <button onClick={onMinus1}>-1</button>
            <button onClick={onReset}>Reset</button>
            <h3>{hello}</h3>
            <div>第一个函数组件：{timer}</div>
        </>
    )
}




export default FunctionState;